﻿using HostedServiceDemo.EfContext;
using HostedServiceDemo.Model;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HostedServiceDemo
{
    public class DBHostedService : IHostedService
    {
        private readonly ILogger _logger;
        private readonly EFContext _context;

        public DBHostedService(ILogger<DBHostedService> logger, EFContext context)
        {
            _logger = logger;
            _context = context;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _context.Database.EnsureDeletedAsync();
            if (await _context.Database.EnsureCreatedAsync())
            {
                if (!_context.QuartInfo.Any())
                {
                    var goodList = new List<QuartzInfo>()
                        {
                            new QuartzInfo(){
                                guid = Guid.NewGuid().ToString(),
                                triggerGroup = "TestGroup1",
                                triggerName = "TestName",
                                cronExpression = "0 0/1 * * * ? ",
                                fullClassName = "HostedServiceDemo.TestJob",
                                jobGroup = "jobGroup1",
                                jobName = "jobName1",
                            },
                        };
                    _context.QuartInfo.AddRange(goodList);
                    await _context.SaveChangesAsync();
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
